<template>
  <PageContainer>
    <el-card style="margin-bottom: 16px;">
      <SearchForm :form-list="searchList" :search-param="searchInfo" @search="handleSearch" @reset="handleReset"  />
    </el-card>

    <el-card>
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="showDialog()">新增</el-button>
      </div>
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
          :width="item.width">
          <template slot-scope="{ row }">
            {{ row[item.prop] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="action" width="200">
          <template slot-scope="{ row }">
            <el-button type="text" @click="handlePreview(row.tableValue)">预览</el-button>
            <el-button type="text" @click="showDialog(row)">编辑</el-button>
            <el-button type="text" @click="handleRemove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 16px; text-align: right" :current-page.sync="pagData.pageNum"
        :page-size.sync="pagData.pageSize" :total="pagData.total" :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>

    <div v-if="tableTitle" style="margin-top: 16px;">
      <ProTable
        ref="table"
        :title="tableTitle"
        :columns="asyncColumns"
      >
      </ProTable>
    </div>

    <BaseDrawer :visible="visible" :title="title" size="50%" :before-close="handleClose" @cancel="handleClose" @ok="handleSubmit">
      <Form ref="formRef" label-width="80px" :form-list="formList" :form-data="formData">
        <template #config>
          <MonacoEditor ref="editor" :value="formData.config" />
        </template>
      </Form>
    </BaseDrawer>

  </PageContainer>
</template>

<script>
import {
  queryApi,
  createApi,
  updateApi,
  getTableConfigByType,
} from "@/api/systemTable.js";
import SearchForm from '../components/SearchForm.vue';
import Form from '../components/Form.vue';
import MonacoEditor from './components/MonacoEditor.vue';

export default {
  props: {
    dictType: {
      type: String,
      default: ''
    },
  },
  components: {
    SearchForm,
    Form,
    MonacoEditor,
  },
  data() {
    return {
      columns: [
        {
          label: "表格名称",
          prop: "tableLabel",
          valueType: 'input',
        },
        {
          label: "表格类型",
          prop: "tableValue",
          valueType: 'input',
        },
        {
          label: "备注",
          prop: "remark",
        },
      ],
      tableData: [],
      searchList: [
        {
          valueType: "input",
          key: "tableLabel",
          label: "表格名称",
        },
        {
          valueType: "input",
          key: "tableValue",
          label: "表格类型",
        },
      ],
      searchInfo: {
        tableLabel: "",
        tableValue: "",
      },
      pagData: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 弹窗属性
      // 弹窗属性
      visible: false,
      title: "",
      formList: [
        {
          label: "表格名称",
          valueType: "input",
          key: "tableLabel",
          itemSpan: 12,
          rules: [{ required: true, message: "请输入表格名称", trigger: "blur" }]
        },
        {
          label: "表格类型",
          valueType: "input",
          key: "tableValue",
          itemSpan: 12,
          rules: [
            { required: true, message: "请输入表格类型", trigger: "blur" },
            {
              validator: (rule, value, callback) => {
                if (!value || value.length < 3) {
                  return callback(new Error('长度不小于3个字符'));
                } else if (!value.includes('_')) {
                  return callback(new Error('必须包含_'));
                } else {
                  callback()
                }
              }, trigger: 'blur'
            }
          ]
        },
        {
          label: "备注",
          valueType: "input",
          key: "remark",
          itemSpan: 24,
        },
        {
          label: "配置",
          valueType: "custom",
          key: "config",
          itemSpan: 24,
        },
      ],
      formData: {
        tableLabel: "",
        tableValue: "",
        remark: "",
        config: JSON.stringify({
          columns: new Array(5).fill({
            label: "label",
            prop: "prop",
          }).map((item, i) => ({
            label: "label" + i,
            prop: "prop" + i,
            search: {
              valueType: i < 4 ? "input" : "select"
            }
          }))
        }, null, 2)
      },
      tableTitle: "",
      asyncColumns: []
    };
  },
  created() {
    this.getTableData()
  },
  methods: {
    getTableData() {
      const { pageNum, pageSize } = this.pagData
      const params = {
        ...this.searchInfo,
        pageNum,
        pageSize
      }
      queryApi(params).then(res => {
        this.tableData = res.data.list
        this.pagData.total = res.data.total
      })
    },
    handleSearch() {
      this.pagData.pageNum = 1
      this.getTableData()
    },
    handleReset() {
      this.searchInfo = Object.assign({}, this.$options.data().searchInfo)
    },
    handleCurrentChange(pageNum) {
      this.pagData.pageNum = pageNum;
      this.getTableData();
    },
    handleSizeChange(pageSize) {
      this.pagData.pageSize = pageSize;
      this.pagData.pageNum = 1;
      this.getTableData();
    },
    showDialog(row) {
      if (!row) {
        this.title = "添加"
      } else {
        this.title = "编辑"
        this.formData = {
          ...row,
        }
      }
      this.visible = true
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          const func = this.title === '添加' ? createApi : updateApi
          const value = this.$refs.editor.getValue()
          const res = await func({
            ...this.formData,
            config: value
          })
          if (res) {
            this.handleClose();
            this.getTableData();
          }
        }
      })
    },
    // 弹窗关闭事件
    handleClose() {
      this.visible = false
      this.$refs.formRef.resetFields()
      this.formData = Object.assign({}, this.$options.data().formData)
    },
    handlePreview(type) {
      this.tableTitle = ""
      getTableConfigByType(type).then(res => {
        const { data } = res
        if (data) {
          this.tableTitle = data.tableLabel
          const value = JSON.parse(data.config)
          console.log('value: ', value);
          this.asyncColumns = value.columns
          console.log('this.asyncColumns: ', this.asyncColumns);
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
